package mock;

import bean.Car;
import com.github.javafaker.Faker;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class CarDataGenerator {
    private static final String DB_URL = "jdbc:mysql://192.168.10.102:3306/driver?useSSL=false&requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    // 缓存 driver_ids 避免重复查询
    private static List<String> driverIdCache = null;
    private static final Random random = new Random();

    /**
     * 从 driver 表中随机获取一个 driver_id
     */
    public static String randomDriverId() {
        if (driverIdCache == null || driverIdCache.isEmpty()) {
            driverIdCache = getAllDriverIds();
        }

        if (driverIdCache == null || driverIdCache.isEmpty()) {
            throw new IllegalStateException("driver 表中没有可用的 driver_id");
        }

        return driverIdCache.get(random.nextInt(driverIdCache.size()));
    }

    /**
     * 获取 driver 表中指定 driver_id 的 car_number, car_type, total_orders
     */
    public static DriverInfo getDriverInfoById(String driverId) {
        String query = "SELECT driver_car_number, driver_car_type, total_orders FROM driver WHERE driver_id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setString(1, driverId);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new DriverInfo(
                            rs.getString("driver_car_number"),
                            rs.getString("driver_car_type"),
                            rs.getString("total_orders")
                    );
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询所有 driver_id
     */
    public static List<String> getAllDriverIds() {
        List<String> driverIds = new ArrayList<>();
        String query = "SELECT driver_id FROM driver";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()) {
                driverIds.add(rs.getString("driver_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (driverIds.isEmpty()) {
            throw new RuntimeException("driver 表中没有可用的 driver_id");
        }

        return driverIds;
    }

    /**
     * 用于保存 driver 表中需要的字段信息
     */
    private static class DriverInfo {
        String carNumber;
        String carType;
        String totalOrders;

        public DriverInfo(String carNumber, String carType, String totalOrders) {
            this.carNumber = carNumber;
            this.carType = carType;
            this.totalOrders = totalOrders;
        }
    }

    public static void main(String[] args) {
        int count = 100;
        if (args.length >= 1) {
            count = Integer.parseInt(args[0]);
        }
        generateData(count);
    }
    public static void generateData(int count ) {

        Faker faker = new Faker(Locale.CHINA);
        List<Car> cars = new ArrayList<>();

        for (long i = 1; i <= count; i++) {
            String driverId = randomDriverId();
            DriverInfo info = getDriverInfoById(driverId);

            if (info == null) {
                System.err.println("无法找到 driver_id = " + driverId + " 的信息");
                continue;
            }
            Car car = Car.builder()
                    .car_id(String.valueOf(i))
                    .driver_id(driverId)
                    .car_type(info.carType)
                    .car_number(info.carNumber)
                    .car_color(generateRandomCarColor(faker))
                    .car_brand(generateRandomCarBrand(faker))
                    .car_seat(generateRandomCarSeat(faker))
                    .total_orders(info.totalOrders)
                    .avg_distance(generateRandomAvgDistance(faker))
                    .build();
            cars.add(car);
        }

        // 批量插入数据库
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);
            String sql = "INSERT INTO car (car_id, driver_id,car_type,car_number,car_color,car_brand,car_seat,total_orders,avg_distance) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                for (int i = 0; i < cars.size(); i++) {
                    Car car = cars.get(i);
                    pstmt.setString(1, car.getCar_id());
                    pstmt.setString(2, car.getDriver_id());
                    pstmt.setString(3, car.getCar_type());
                    pstmt.setString(4, car.getCar_number());
                    pstmt.setString(5, car.getCar_color());
                    pstmt.setString(6, car.getCar_brand());
                    pstmt.setString(7, car.getCar_seat());
                    pstmt.setString(8, car.getTotal_orders());
                    pstmt.setDouble(9, car.getAvg_distance());
                    pstmt.addBatch();

                    if ((i + 1) % BATCH_SIZE == 0) {
                        pstmt.executeBatch();
                    }
                }
                pstmt.executeBatch();
                conn.commit();
                System.out.println("成功插入" + count + "条数据");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static double generateRandomAvgDistance(Faker faker) {
        return Math.round(faker.number().randomDouble(2, 15, 300) * 100.0) / 100.0;
    }

    private static String generateRandomCarSeat(Faker faker) {
        String[] seats = {"2座", "4座", "5座", "7座", "8座",  "10座"};
        return seats[faker.random().nextInt(seats.length)];
    }

    private static String generateRandomTotalOrders(Faker faker) {
        return String.valueOf(faker.random().nextInt(1000));
    }

    private static String generateValidCarNumber(Faker faker) {
        String[] provinceAbbreviations = {"京", "津", "沪", "渝", "冀", "豫", "云", "辽", "黑", "湘", "皖", "鲁", "新", "苏", "浙", "赣", "鄂", "桂", "甘", "晋", "蒙", "陕", "吉", "闽", "贵", "粤", "青", "藏", "琼"};
        // 定义车牌字母部分（去掉I和O，避免与数字混淆）
        String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        // 随机选择省份简称
        String province = provinceAbbreviations[faker.random().nextInt(provinceAbbreviations.length)];
        // 随机选择字母
        String letter = letters[faker.random().nextInt(letters.length)];
        // 生成5位随机数字
        String number = String.format("%05d", faker.random().nextInt(100000));

        // 组合成完整的车牌号码
        return province + letter + number;

    }

    private static String generateRandomCarColor(Faker faker) {
        String[] colors = {"红色", "蓝色", "黄色", "绿色", "紫色", "橙色", "黑色", "白色", "棕色", "灰色"};
        return colors[faker.random().nextInt(colors.length)];
    }
    private static String generateRandomCarType(Faker faker) {
        String[] carTypes = {"SUV", "MPV", "轿车", "面包车", "商务车", "皮卡"};
        return carTypes[faker.random().nextInt(carTypes.length)];
    }
    public static String generateRandomCarBrand(Faker faker) {
        String[] brands = {"比亚迪", "丰田", "福特","吉利","长城","本田","大众","宝马","奔驰","标致","奥迪","雪佛兰","沃尔沃","奇瑞","五菱","路虎","捷豹"};
        return brands[faker.random().nextInt(brands.length)];
    }



}
